PHP Ternary Operator With Elseif Example

105

var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
$result = $condition ? 'foo' : 'bar';
$foo = your_value;
$bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
echo $bar;
//Use this format before reducing the expression to one liner
$var=4; //Change value to test
echo "Format result: ";

echo($var === 1)    ? 'one'     : //if      NB.=> $varname = || echo || print || var_dump(ternary statement inside); can only be (placed at the start/wrapping) of the statement. 
    (($var === 2)   ? 'two'     : //elseif
    (($var === 3)   ? 'three'   : //elseif
    (($var === 4)   ? 'four'    : //elseif
    'false'                       //else
    )));                          //extra tip: closing brackets = totalnumber of conditions - 1 

// Then  echo($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))); 
echo "<br/>";
var_dump("Short result: ", ($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))) );

Comments

Submit
0 Comments